<template>
  <div class="login-container">
    <div class="login-content">
      <div class="login-box">
        <div class="login-header">
          <h2>欢迎登录</h2>
          <p>智慧医疗服务平台</p>
          </div>
          
          <el-form :model="form" :rules="rules" ref="loginForm" class="login-form">
            <el-form-item prop="username">
              <el-input 
                v-model="form.username" 
              placeholder="请输入用户名/邮箱"
              size="large"
              clearable
              prefix-icon="User"
            />
            </el-form-item>
            
            <el-form-item prop="password">
              <el-input 
                v-model="form.password" 
                type="password" 
                placeholder="请输入密码"
              size="large"
                show-password
              clearable
              prefix-icon="Lock"
            />
            </el-form-item>
            
            <!-- 错误信息提示 -->
            <div v-if="loginError" class="login-error">
              <el-icon><WarningFilled /></el-icon>
              <span>{{ loginError }}</span>
            </div>
            
          <div class="login-options">
            <el-checkbox v-model="rememberMe">记住我</el-checkbox>
            <el-link type="primary" :underline="false">忘记密码?</el-link>
            </div>
            
            <el-button 
              type="primary" 
              class="login-button" 
              :loading="loading"
              @click="handleLogin"
            >
              登录
            </el-button>
            
          <div class="login-footer">
            <p>还没有账号？ <el-link type="primary" :underline="false" @click="toRegister">立即注册</el-link></p>
            <p class="back-to-home">
              <el-link type="info" :underline="false" @click="backToPortal">
                <el-icon><ArrowLeft /></el-icon> 返回首页
              </el-link>
            </p>
            </div>
          </el-form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { authAPI } from '@/utils/api'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const userStore = useUserStore()
const loginForm = ref(null)
const loading = ref(false)
const rememberMe = ref(false)
const loginError = ref('') // 新增登录错误信息

const form = reactive({
  username: '',
  password: ''
})

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
}

// 处理登录
const handleLogin = () => {
  loginError.value = '' // 重置错误信息
  
  loginForm.value.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true
        const res = await authAPI.login(form)
        
        if (res.success) {
          userStore.setToken(res.data.accessToken)
          userStore.setUserInfo(res.data.user)
          
          // 如果勾选了"记住我"，将凭据保存到localStorage
          if (rememberMe.value) {
            localStorage.setItem('remember_username', form.username)
          } else {
            localStorage.removeItem('remember_username')
          }
          
          // 登录成功提示
          ElMessage.success('登录成功')
          
          // 触发自定义用户登录事件
          window.dispatchEvent(new Event('user-login'))
          
          // 设置菜单路由
          // 如果是管理员，直接获取所有路由
          if (userStore.userRole === 'admin') {
            // 从router模块获取所有路由
            const { asyncRoutes } = await import('@/router')
            userStore.setMenuRoutes(asyncRoutes)
          } else {
            // 根据权限筛选路由
            const permissionModule = await import('@/utils/permission')
            const accessibleRoutes = permissionModule.generateAccessibleRoutes(
              userStore.permissions,
              userStore.userRole
            )
            userStore.setMenuRoutes(accessibleRoutes)
          }
          
          // 根据角色决定跳转目标
          if (userStore.userRole === 'admin') {
            // 管理员登录后，跳转到系统管理页面
            router.push('/system/users')
          } else if (userStore.userRole === 'doctor') {
            // 医生登录后，跳转到医生工作站
            router.push('/portal/doctor/workstation')
          } else {
            // 普通用户（如患者）登录后，跳转到门户首页
            router.push('/portal')
          }
        } else {
          // API返回了错误信息但HTTP状态是200
          loginError.value = res.message || '用户名或密码错误'
          ElMessage.error(loginError.value)
        }
      } catch (error) {
        console.error('登录错误:', error)
        // 设置错误信息显示在表单下方
        if (error.response && error.response.data && error.response.data.message) {
          loginError.value = error.response.data.message
        } else {
          loginError.value = '用户名或密码错误'
        }
        ElMessage.error(loginError.value)
      } finally {
        loading.value = false
      }
    }
  })
}

// 跳转到注册页
const toRegister = () => {
  router.push('/register')
}

// 返回门户首页
const backToPortal = () => {
  router.push('/portal')
}
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  background: linear-gradient(to right, #e6f7ff, #f0f9ff);
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
}

.login-content {
  width: 100%;
  max-width: 1200px;
  display: flex;
  justify-content: center;
}

.login-box {
  width: 450px;
  background: white;
  border-radius: 10px;
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
  padding: 40px;
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-header h2 {
  font-size: 28px;
  color: #333;
  margin-bottom: 10px;
}

.login-header p {
  font-size: 16px;
  color: #666;
  margin: 0;
}

.login-form {
  margin-top: 20px;
}

.login-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.login-button {
  width: 100%;
  height: 44px;
  font-size: 16px;
}

.login-footer {
  margin-top: 30px;
  text-align: center;
}

.login-footer p {
  margin: 10px 0;
  color: #666;
}

.back-to-home {
  margin-top: 20px;
}

.login-error {
  display: flex;
  align-items: center;
  color: #f56c6c;
  font-size: 14px;
  margin-bottom: 15px;
  padding: 8px 12px;
  background-color: #fef0f0;
  border-radius: 4px;
}

.login-error .el-icon {
  margin-right: 8px;
  font-size: 16px;
}

@media (max-width: 768px) {
  .login-box {
    width: 100%;
    max-width: 450px;
    padding: 30px 20px;
  }
}
</style> 